package com.echo.register.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.echo.register.client.cmn.DictFeignClient;
import com.echo.register.common.exception.RegisterException;
import com.echo.register.common.helper.JwtHelper;
import com.echo.register.common.result.ResultCodeEnum;
import com.echo.register.enums.AuthStatusEnum;
import com.echo.register.enums.DictEnum;
import com.echo.register.model.base.BaseEntity;
import com.echo.register.model.user.Patient;
import com.echo.register.model.user.UserInfo;
import com.echo.register.model.user.UserLoginRecord;
import com.echo.register.user.mapper.UserInfoMapper;
import com.echo.register.user.service.PatientService;
import com.echo.register.user.service.UserInfoService;
import com.echo.register.user.service.UserLoginRecordService;
import com.echo.register.vo.user.LoginVo;
import com.echo.register.vo.user.UserAuthVo;
import com.echo.register.vo.user.UserInfoQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: UserInfoServiceImpl
 * @Package: com.echo.register.user.service.impl
 * @Description:
 * @Author 谢同学
 * @Create 2023/12/22 19:07
 * @Version 1.0
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserLoginRecordService userLoginRecordService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private DictFeignClient dictFeignClient;

    @Autowired
    private PatientService patientService;


    /**
     * 登录
     *
     * @param loginVo 用户信息
     * @return 统一返回map
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        // 最终结果封装
        Map<String, Object> result = new HashMap<>();
        // 校验数据
        String phone = loginVo.getPhone();// 手机号
        String code = loginVo.getCode(); // 验证码
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        // 验证码校验
        if (!code.equals(redisTemplate.opsForValue().get(phone))) {
            throw new RegisterException(ResultCodeEnum.CODE_ERROR);
        }
        // 校验手机号是否唯一
        UserInfo userInfo = baseMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        if (userInfo == null) {
            // 如果不存在 注册
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setAuthStatus(0);// 认证状态（0：未认证 1：认证中 2：认证成功 -1：认证失败
            userInfo.setStatus(1); // 状态（0：锁定 1：正常）
            baseMapper.insert(userInfo);
        }
        // 校验手机号是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new RegisterException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        // 登录记录
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(loginVo.getIp());
        userLoginRecordService.insert(userLoginRecord);
        // 返回页面名称
        String name = userInfo.getNickName();
        // 如果没有用户名返回昵称或者手机号
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        // jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        result.put("name", name);
        result.put("token", token);// token 后面实现
        return result;
    }

    /**
     * 用户认证
     *
     * @param userId     用户id
     * @param userAuthVo 认证信息
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        // 根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        if (userInfo != null) {
            // 设置认证信息
            userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus()); // 认证信息
            BeanUtils.copyProperties(userAuthVo, userInfo);
            // 修改登录信息
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public UserInfo getById(Long id) {
        UserInfo userInfo = baseMapper.selectById(id);
        //处理数据
        if (userInfo != null) {
            this.packUserInfo(userInfo);
        }
        return userInfo;
    }

    /**
     * 分页查询用户列表
     *
     * @param page
     * @param limit
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public Page<UserInfo> selectPage(Long page, Long limit, UserInfoQueryVo userInfoQueryVo) {
        // 构建分页条件
        Page<UserInfo> pageParam = new Page<>(page, limit);
        // 构建查询条件
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<UserInfo>()
                .like(!StringUtils.isEmpty(userInfoQueryVo.getKeyword()), UserInfo::getName, userInfoQueryVo.getKeyword())
                .eq(!StringUtils.isEmpty(userInfoQueryVo.getStatus()), UserInfo::getStatus, userInfoQueryVo.getStatus())
                .eq(!StringUtils.isEmpty(userInfoQueryVo.getAuthStatus()), UserInfo::getAuthStatus, userInfoQueryVo.getAuthStatus())
                .eq(BaseEntity::getIsDeleted, 0)
                .ge(!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeBegin()), UserInfo::getName, userInfoQueryVo.getCreateTimeBegin())
                .le(!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeEnd()), UserInfo::getCreateTime, userInfoQueryVo.getCreateTimeEnd());

        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        // 数据处理
        userInfoPage.getRecords().forEach(this::packUserInfo);
        return userInfoPage;
    }

    /**
     * 解锁锁定用户
     *
     * @param userId 用户id
     * @param status 状态
     */
    @Override
    public void lock(Long userId, Integer status) {
        // 校验参数
        if (status == 1 || status == 0) {
            // 查询初始状态
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            // 更新状态
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 详情信息
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> result = new HashMap<>();
        // 根据id 查询用户信息
        UserInfo userInfo = getById(userId);
        this.packUserInfo(userInfo);
        result.put("userInfo", userInfo);
        // 查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        result.put("patientList", patientList);
        return result;
    }

    /**
     * 认证审批
     *
     * @param userId
     * @param authStatus 2：通过 -1：不通过
     */
    @Override
    public void approval(Long userId, Integer authStatus) {
        // 校验参数
        if (authStatus == 2 || authStatus == -1) {
            UserInfo userInfo = getById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 数据处理
     *
     * @param userInfo
     */
    private void packUserInfo(UserInfo userInfo) {
        if (userInfo == null) {
            return;
        }
        String authStatusString = AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus());// 认证状态
        // 状态
        String statusString = userInfo.getStatus() == 1 ? "正常" : "锁定";
        // 证件类型
        String certificatesTypeString = null;
        if (userInfo.getCertificatesType() != null) {
            certificatesTypeString = dictFeignClient.getName(DictEnum.CERTIFICATES_TYPE.getDictCode(), userInfo.getCertificatesType());
        }
        userInfo.getParam().put("statusString", statusString);
        userInfo.getParam().put("authStatusString", authStatusString);
        userInfo.getParam().put("certificatesTypeString", certificatesTypeString);
    }
}
